package com.mspbots.cw.amqp.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.amqp.BaseReceiver;
import com.mspbots.cw.amqp.model.Subdata;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * com.mspbots.cw.amqp.receivers.SubdataReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/27
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class SubdataReceiver extends BaseReceiver {

    @RabbitListener(queues = "wise.subdata")
    public void processMessage(JsonNode data) {
        Subdata subdata = Subdata.builder()
                .tenantId(data.get("tenantId").asInt())
                .cwId(data.get("id").asLong())
                .type(data.get("subDataType").asText())
                .updatedTime(ObjectUtils.isEmpty(data.findValue("lastUpdated")) ? null :
                        LocalDateTime.parse(data.findValue("lastUpdated").asText(),
                                DateTimeFormatter.ISO_ZONED_DATE_TIME))
                .syncTime(LocalDateTime.now())
                .name(data.get("name").asText())
                .extend(data).build();

        Optional<Long> id = this.databaseClient.execute("select id from tenant_subdata " +
                "where tenant_id =:tenantId and cw_id =:cwId and type=:type")
                .as(Long.class)
                .bind("tenantId", subdata.getTenantId())
                .bind("cwId", subdata.getCwId())
                .bind("type", subdata.getType())
                .fetch().one().blockOptional();

        if (id.isPresent() && id.get() > 0) {
            log.debug("Receiver schedules tenant id:{},cw id:{}, update id:{}",
                    subdata.getTenantId(), subdata.getCwId(), id.get());
            subdata.setId(id.get());
            this.databaseClient.update().table(Subdata.class).using(subdata)
                    .fetch().rowsUpdated().block();
        } else {
            this.databaseClient.insert().into(Subdata.class).using(subdata)
                    .fetch().rowsUpdated().block();
        }
    }
}
